package com.example.aacwebdemo.h2.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;


import javax.sql.DataSource;

/**
 * @author zhao.xin06679
 * @date 2021年06月18日 13:43
 */
@Configuration
public class H2DataSourceConfig {

    @Value("classpath:db/schema.sql")
    private Resource schemaScript;

    @Value("classpath:db/db.sql")
    private Resource dataScript;

    @Bean(name = "h2")
    @Qualifier("h2")
    @ConfigurationProperties(prefix="spring.datasource.h2")
    DataSource h2(){

        return DataSourceBuilder.create().build();
    }

    @Bean(name = "h2JdbcTemplate")
    JdbcTemplate h2JdbcTemplate(@Autowired @Qualifier("h2") DataSource h2){
        return new JdbcTemplate(h2);
    }



    @Bean
    public DataSourceInitializer dataSourceInitializer(final DataSource dataSource) {
        final DataSourceInitializer initializer = new DataSourceInitializer();
        initializer.setDataSource(dataSource);
        initializer.setDatabasePopulator(databasePopulator());
        return initializer;
    }

    private DatabasePopulator databasePopulator() {
        final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
        populator.addScript(schemaScript);
      //  populator.addScript(dataScript);
        return populator;
    }

}
